<template>
  <div :class="['merak-container-has-aside', { 'merak-container-has-add': visibleAdd }]" curPageName="goods_allocation">
    <div class="merak-aside">
      <div class="title">{{ $t(`merak.${props.type}`) }}</div>
      <el-input
        v-model="treeState.filter"
        :placeholder="$t('merak.placeholder_filter')"
        :suffix-icon="Search"
        @input="value => treeRef?.filter(value)"
      />
      <div class="tree-wrapper">
        <el-scrollbar>
          <el-tree
            class="merakTree"
            ref="treeRef"
            node-key="id"
            :data="treeState.data"
            :props="{ children: 'childs' }"
            :class="expandedKey && expandedKeys[0].indexOf('-') != -1 ? '' : 'noThree'"
            :default-expanded-keys="expandedKeys"
            :filter-node-method="(value, tree) => tree.label.includes(value)"
            @current-change="handleCurrentChange"
          >
            <template #default="{ node, data }">
              <div class="tree_item">
                <div class="tree_name">{{ node.label }}</div>
                <el-icon v-if="data.is_label && data.is_label == 1"><PriceTag /></el-icon>
              </div>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
    <Table
      ref="saleRef"
      :key="treeState.value"
      :type="props.type"
      :label="treeState.isLabel"
      :queueId="queueId"
      :treeSelected="treeState.value"
      :setValue="setId"
      @add="handleAdd"
    />

    <Transition name="fade" mode="out-in">
      <BuiltProduct
        v-if="visibleAdd"
        :id="treeState.value ?? ''"
        :title="treeState.title ?? ''"
        :suite="is_suite"
        :copyData="copyState"
        @close="handleClose"
      />
    </Transition>
  </div>
</template>

<script setup lang="ts" name="PageList">
import { ref, reactive, computed, onMounted,getCurrentInstance } from "vue";

import { useRoute } from "vue-router";

import { ElInput, ElScrollbar, ElTree, ElTabs, ElTabPane } from "element-plus";

import { Search } from "@element-plus/icons-vue";
import { useTabsStore } from "@/stores/modules/tabs";
import Table from "./TableMessage.vue";

// import AddQifa from "./AddQifa.vue";
// import AddClearance from "./AddClearance.vue";
import BuiltProduct from "@/views/goodsArchive/BuiltProduct/index.vue";

import useLoading from "@/hooks/useLoading";

import { ResultEnum } from "@/enums/httpEnum";
const { proxy } = getCurrentInstance();
import { RouteType, TreeType, getSearcList, getDailyNecessitiesTree } from "@/api/modules/goodsArchive/list/information";
const tabStore = useTabsStore();
const tabsMenuList = computed(() => tabStore.tabsMenuList);
const props = defineProps<{
  type: RouteType;
}>();

const route = useRoute();

const { queueLoading, queueId } = useLoading();

const treeRef = ref<InstanceType<typeof ElTree>>();
const saleRef = ref<InstanceType<typeof Sales>>();

//const clearanceRef = ref<InstanceType<typeof Clearance>>();

const visibleAdd = ref(false);

const setId = ref<string | number>();

const is_suite = ref<0 | 1>(0);

const copyState = reactive<{
  type_id?: string | number;
  type_title?: string;
  product_id?: string | number;
}>({});

const treeState = reactive<{
  data: TreeType[];
  value?: string;
  title?: string;
  filter?: any;
  isLabel?:any;
}>({ data: [] });

const expandedKeys = computed(() => {
  const arr: string[] = [];
  if (!!route.query.key) {
    const routeKeys = route.query.key.toString().split("-");
    arr.push(routeKeys[0]);
  }
  return arr;
});

// 树点击
const handleCurrentChange: InstanceType<typeof ElTree>["onCurrent-change"] = (data, treeNode) => {
  if (!treeNode.isLeaf) return;
  saleRef.value.oncancel();
  const url = new URL(location.href);
  if (data.id === "all") {
    url.searchParams.delete("key");
    url.searchParams.delete("set");
	url.searchParams.set("label", 1);
	treeState.isLabel = 1;
  } else {
    url.searchParams.set("key", data.id.toString());
    url.searchParams.set("set", data.set.toString());
	url.searchParams.set("label", data.is_label);
	treeState.isLabel = data.is_label;
}
treeState.value = data.value.toString();
treeState.title = data.label;

  if (data.set != undefined) {
    setId.value = data.set.toString();
  }
  // const tabIndex = tabStore.tabsMenuList.findIndex(item=>route.name == item.name);
  // if(tabIndex != -1){
	 //  let listMenu =  tabStore.tabsMenuList
	 //  listMenu[tabIndex].path = url.pathname + url.search;
	 //  tabStore.setTabs(listMenu);
  // }

  // 记录浏览器参数
  history.pushState({}, "", url);
  treeRef.value?.setCheckedKeys([data.id]);
};

// 添加页面
const handleAdd = ({ copyId, typeId, typeTitle, suite }: { copyId?: string | number; typeId?: string | number; typeTitle?: string, suite?: 0 | 1 }) => {
  copyState.type_id = typeId;
  copyState.type_title = typeTitle;
  copyState.product_id = copyId;
  is_suite.value = !!suite ? 1 : 0;
  visibleAdd.value = true;
};

// 关闭添加页面
const handleClose = (refresh: boolean) => {
  if (refresh) {
    // 刷新页面
    saleRef.value.onReload();
  }
  visibleAdd.value = false;
};

onMounted(() => {

  let data = {
    type: props.type,
    is_paking: 1
  };
  getDailyNecessitiesTree(data, queueId.value).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      const generate = (list: TreeType[], parentId?: string | number) => {
        const arr: TreeType[] = [];
        list.forEach(item => {
          const payload: TreeType = {
            id: `${!!parentId ? parentId + "-" : ""}${item.value}`,
            value: item.value,
            label: item.label,
            set: item.set
          };
          if (!!item.childs?.length) {
            payload.childs = generate(item.childs, item.value);
          } else {
			  payload.is_label = item.is_label
		  }
          arr.push(payload);
        });
        return arr;
      };
      const findOption = (key: string, options: any[])=> {
        let result:Record<string,any> | undefined;
        for(let option of options) {
          if (option.id === key) {
            result= option
            break
          } else if (!!findOption(key, [...option?.childs??[]])) {
            result = findOption(key, [...option?.childs??[]])
          }
        }
        return result
      }
      treeState.data = [{ id: "all", value: "0", label: proxy!.$t("merak.all"), }, ...generate(data)];
      if (!!route.query.key) {
        const routeKeys = route.query.key.toString().split("-");
        treeState.value = routeKeys[routeKeys.length - 1];
        // console.log(treeState.value, treeState.data)
		treeState.title =findOption(route.query.key.toString(), treeState.data)?.label;
		treeState.isLabel = route.query.label;
        setId.value = route.query.set;
        treeRef.value?.setCheckedKeys([route.query.key.toString()]);
      } else {
        treeState.value = "0";
		treeState.title = '';
        treeRef.value?.setCheckedKeys(["all"]);
      }
    }
  });
});
</script>

<style scoped lang="scss">
.tree_item {
  display: flex;
  padding: 7px 0;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  .el-icon {
    padding-right: 10px;
  }
  .tree_name {
  }
}
.merak-container-has-aside {
  position: relative;
  &.merak-container-has-add > :not(.add-product-container) {
    opacity: 0;
  }
}

.merak-aside {
  display: flex;
  flex-direction: column;

  & > :not(:first-child) {
    margin-top: var(--merak-space);
  }

  & > .tree-wrapper {
    flex: 1;
    min-height: 0;
  }

  .title {
    font-size: 16px;
  }
}

.el-tree {
  :deep(.el-tree-node.is-checked .el-tree-node__content:has(.is-leaf)) {
    color: #fff !important;
    background-color: var(--el-color-primary) !important;
  }
}

.el-tabs {
  display: flex;
  flex-direction: column;
  margin-top: calc(0px - var(--merak-space));
  height: calc(100% + var(--merak-space));

  :deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }

  :deep(.el-tabs__content) {
    flex: 1;
    min-height: 0;

    .el-tab-pane {
      height: 100%;

      & > div {
        height: 100%;
      }
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
